package com.zggk.framework.controller.fileupload;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.platform.common.bean.Message;
import com.platform.framework.controller.BaseController;
import com.platform.framework.entity.file.BaseFileEntity;
import com.platform.framework.entity.file.CataLogue;
import com.platform.framework.service.file.CataLogueService;
import com.zggk.framework.service.file.BaseFileEntityService;
import com.zggk.framework.utils.FileUtils;
import com.zggk.framework.utils.ReturnMessage;
import com.zggk.framework.utils.ThumbnailatorUtils;

import io.minio.MinioClient;

@RestController
public class FileUploadController extends BaseController {

	@Autowired
	CataLogueService cataLogueService;
	@Autowired
	BaseFileEntityService baseFileEntityService;
	
	
	
	/**
	 * 
	 * @Description 组织保存在minio的文件具体路径的方法
	 * @author 张立增[zhanglizeng] Tel：18860126570
	 * @createDate 2018年4月28日 上午10:09:54
	 */
	public String getSaveMinioPath(HttpServletRequest request) {
		String belongProject = request.getParameter("belongProject");   //所属项目
		String firstMenu = request.getParameter("firstMenu");           //一级目录
		String secondMenu = request.getParameter("secondMenu");         //二级目录
		String fileType = request.getParameter("fileType");             //文件类型
		String path = "我的文档/"+getUserCode();
		if(belongProject != null && belongProject.length() > 0){
			path += "/"+belongProject;
		}
		if(firstMenu != null && firstMenu.length() > 0){
			path += "/"+firstMenu;
		}
		if(secondMenu != null && secondMenu.length() > 0){
			path += "/"+secondMenu;
		}
		if(fileType != null && fileType.length() > 0){
			path += "/"+fileType;
		}
		return path+"/";
	}
	
	/**
	 * 
	 * @Description 更新文件名称的方法
	 * @author 张立增[zhanglizeng] Tel：18860126570
	 * @param request 
	 * @param file 
	 * @createDate 2018年4月23日 下午5:49:24
	 */
	public void updateFile(String fileName,BaseFileEntity existBaseFileEntity)throws Exception {
		existBaseFileEntity.setFileName(fileName);
		existBaseFileEntity.setUpdateUserCode(getUserCode());
		existBaseFileEntity.setUpdateUserName(this.getUserEntity().getName());
		baseFileEntityService.saveFileInfo(existBaseFileEntity); 
	}
	
	/**
	 * 
	 * @Description 得到处理过后的文件输入流
	 * @author 张立增[zhanglizeng] Tel：18860126570
	 * @param inputStream 
	 * @return    
	 * @throws IOException 
	 * @createDate 2018年4月23日 下午3:33:06    
	 */
	public ByteArrayOutputStream getDealInputStream(InputStream inputStream) throws IOException {
		ByteArrayOutputStream arrayStream = new ByteArrayOutputStream();
		byte[] b = new byte[1024];
		int len;    
		while ((len = inputStream.read(b)) > -1) {
			arrayStream.write(b, 0, len);
		}
		arrayStream.flush();
		return arrayStream;
	}

	/**
	 * 
	 * @Description 保存记录上传文件实体信息的方法（用于后台管理文件操作）
	 * @author 张立增[zhanglizeng] Tel：18860126570    
	 * @param filePath 
	 * @createDate 2018年4月22日 下午2:46:50
	 */
	public void saveUploadFileEntity(MultipartFile file, String md5,String absolutePath,String newFileName,String fileType,String fileId, String filePath)throws Exception{
		BaseFileEntity baseFileEntity = new BaseFileEntity();
		baseFileEntity.setId(fileId);
		baseFileEntity.setFileName(file.getOriginalFilename());
		baseFileEntity.setFileNewName(newFileName);     
		baseFileEntity.setFileDirectory("lwzx");
		baseFileEntity.setFilePath(filePath);   
		baseFileEntity.setAbsolutePath(absolutePath);
		baseFileEntity.setFileSize(file.getSize());
		baseFileEntity.setFileType(fileType);
		baseFileEntity.setFileMd5(md5);
		baseFileEntity.setCreateUserCode(this.getUserCode());
		baseFileEntity.setCreateUserName(this.getUserEntity().getName());
		baseFileEntity.setCreateTime(new Date());
		baseFileEntityService.saveFileInfo(baseFileEntity);
	}
	
	/**
	 * 文件上传页面
	 * 
	 * @return
	 */
	@RequestMapping("/upload")
	public ModelAndView fileUpload(Model model) {
		ModelAndView mv = new ModelAndView("fileUpoload/index");
		return mv;
	}

	/**
	 * 一般的文件上传页面
	 * 
	 * @return
	 */
	@RequestMapping("/commonUpload")
	public ModelAndView commonFileUpload(Model model) {
		ModelAndView mv = new ModelAndView("fileUpoload/commonIndex");
		return mv;
	}
	/**
	 * 
	 * @Description 全资产上传页面跳转
	 * @author 尹强[yinqiang] Email:2259441906@qq.com Tel:18181725967
	 * @createDate 2018年4月23日 上午10:51:51
	 */
	@RequestMapping("/dataIntegraUpload")
	public ModelAndView dataIntegraFileUpload(Model model) {
		ModelAndView mv = new ModelAndView("fileUpoload/dataIntegraIndex");
		return mv;
	}
	/**
	 * 
	 * @Description 跳转普通上传解析
	 * @author 尹强[yinqiang] Email:2259441906@qq.com Tel:18181725967
	 * @throws
	 * @throws 
	 * @createDate 2018年8月4日 下午3:55:42
	 */
	@RequestMapping("/resolveIndex")
	public ModelAndView resolveIndex(Model model) {
		ModelAndView mv = new ModelAndView("fileUpoload/resolveIndex");
		return mv;
	}
	/**
	 * 
	 * @Description
	 * @author 尹强[yinqiang] Email:2259441906@qq.com Tel:18181725967
	 * @createDate 2018年5月7日 下午2:35:02
	 */
	@RequestMapping("/resolveFile")
	public ModelAndView resolveFileUpload(Model model) {
		ModelAndView mv = new ModelAndView("fileUpoload/resolveIndex");
		return mv;
	}
	/**
	 * 文件上传操作
	 * 
	 * @Description .
	 * @author 李增冰[lizengbing] Tel13807031023
	 * @param file
	 * @param request
	 */
	@RequestMapping("/uploadFile")
	public String uploadFile(@RequestParam("fileId") MultipartFile file, HttpServletRequest request) {
		ReturnMessage msg = new ReturnMessage();
		try {
			InputStream fileInput = file.getInputStream();
			//文件保存路径
			String path = request.getParameter("path");
			System.out.println(path);
			//获取文件的MD5
			String md5 = DigestUtils.md5Hex(fileInput);
			BaseFileEntity existBaseFileEntity = baseFileEntityService.isExistFile(md5);
			if(existBaseFileEntity == null) {
				MinioClient minioClient = FileUtils.getInstance();
				boolean isExist = minioClient.bucketExists("lwzx");
				if (isExist) {
					System.out.println("Bucket already exists.");
				} else {
					// Make a new bucket called asiatrip to hold a zip file of photos.
					minioClient.makeBucket("lwzx");
				}
				//Generate symmetric 256 bit AES key.
				  KeyGenerator symKeyGenerator = KeyGenerator.getInstance("AES");
				  symKeyGenerator.init(128);
				  SecretKey symKey = symKeyGenerator.generateKey();
	
				// Upload  file to the bucket with putObject
				System.out.println("文件长度："+file.getSize());
				minioClient.putObject("lwzx",path+"/"+file.getOriginalFilename(), fileInput,fileInput.available(),"application/octet-stream",symKey);
				fileInput.close();
				BaseFileEntity baseFile = new BaseFileEntity();
				baseFile.setId(getUUID());
				baseFile.setFileName(file.getOriginalFilename());
				baseFile.setCreateTime(new Date());   
				baseFile.setCreateUserCode(getUserCode());
				baseFile.setAbsolutePath(minioClient.getObjectUrl("lwzx", path+"/"+file.getOriginalFilename()));
				baseFile.setFileSize(file.getSize());
				baseFile.setFileMd5(md5);
				baseFileEntityService.saveFileInfo(baseFile);
				msg.setStatus("true");
				msg.setData(file.getOriginalFilename()+"上传成功");
				System.out.println(file.getOriginalFilename()+" is uploaded successfully");
			}else {
				msg.setStatus("false");
				msg.setData(file.getOriginalFilename()+"已存在，请勿重复上传！");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			msg.setStatus("false");
			msg.setData(e.toString());
		}
		return JSONObject.toJSONString(msg);
	}
	
	/**
	 * 
	  * @Description 普通文件上传操作
	  * @author 杜天[dutian] Email:13594731440@163.com Tel:17600471932
	  * @param file
	  * @param request
	  * @return
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping("/uploadCommonFile")
	public String uploadCommonFile(@RequestParam("fileId") MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
		ReturnMessage msg = new ReturnMessage();
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		try {
			InputStream fileInput = file.getInputStream();
			ByteArrayOutputStream fileOut = new ByteArrayOutputStream();
			byte[] b = new byte[1024];
			int len;
			while ((len = fileInput.read(b)) > -1) {
				fileOut.write(b, 0, len);
			}
			fileOut.flush();
			//获得文件名
            String fileName = file.getOriginalFilename();
            String path="我的文档";
            // 获取文件后缀名并转化为小写，用于后续比较
            String fileType = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()).toLowerCase();
            InputStream thumbsImg =null;
			String md5 = DigestUtils.md5Hex(file.getInputStream());
			BaseFileEntity existBaseFileEntity = baseFileEntityService.isExistFile(md5);
			if(existBaseFileEntity == null) {
				MinioClient minioClient = FileUtils.getInstance();
				boolean isExist = minioClient.bucketExists("lwzx");
				if (isExist) {
					System.out.println("Bucket already exists.");
				} else {
					// Make a new bucket called asiatrip to hold a zip file of photos.
					minioClient.makeBucket("lwzx");
				}
				// Upload  file to the bucket with putObject
				System.out.println("文件长度："+file.getSize());
				String newFileName=getUUID()+"."+fileType;
				//上传文件,如果是图片类型,处理缩略图上传到"我的图片/thumbs"
				 if(FileUtils.isImage(fileType)) {
			        	path="我的图片";
			        	InputStream thumInput = new BufferedInputStream(new ByteArrayInputStream(fileOut.toByteArray()));
			        	thumbsImg= ThumbnailatorUtils.getThumbsImg(thumInput);// 获取缩略图流
			        	thumInput.close();
			        	//创建目录thumbs
						minioClient.putObject("lwzx", path+"/"+this.getUserCode()+"/thumbs/"+newFileName,thumbsImg,thumbsImg.available(),"application/octet-stream");
						thumbsImg.close();
				 }
				InputStream orgInput = new BufferedInputStream(new ByteArrayInputStream(fileOut.toByteArray()));
				minioClient.putObject("lwzx",path+"/"+this.getUserCode()+"/"+newFileName, orgInput,orgInput.available(),"application/octet-stream");
				fileInput.close();
				BaseFileEntity baseFileEntity = new BaseFileEntity();
				baseFileEntity.setId(getUUID());
				baseFileEntity.setFileName(fileName);
				baseFileEntity.setFileNewName(newFileName);
				baseFileEntity.setFileDirectory("lwzx");
				baseFileEntity.setFilePath(path+"/"+this.getUserCode()+"/");
				baseFileEntity.setAbsolutePath(minioClient.getObjectUrl("lwzx", path+"/"+this.getUserCode()+"/"+newFileName));
				baseFileEntity.setFileSize(file.getSize());
				baseFileEntity.setFileType(fileType);
				baseFileEntity.setFileMd5(md5);
				baseFileEntity.setCreateUserCode(this.getUserCode());
				baseFileEntity.setCreateUserName(this.getUserEntity().getName());
				baseFileEntity.setCreateTime(new Date());
				baseFileEntity.setUpdateUserCode(this.getUserCode());
				baseFileEntity.setUpdateUserName(this.getUserEntity().getName());
				baseFileEntityService.saveFileInfo(baseFileEntity);
			}else {
				existBaseFileEntity.setFileName(fileName);
				baseFileEntityService.saveFileInfo(existBaseFileEntity);
			}
			msg.setStatus("true");
			msg.setData(file.getOriginalFilename()+"上传成功");
			System.out.println(file.getOriginalFilename()+" is uploaded successfully");
		} catch (Exception e) {
			e.printStackTrace();
			msg.setStatus("false");
			msg.setData(e.toString());
		}
		return JSONObject.toJSONString(msg);
	}
	/**
	 * 
	 * @Description 上传excel
	 * @author 尹强[yinqiang] Email:2259441906@qq.com Tel:18181725967
	 * @createDate 2018年5月7日 上午11:53:41
	 */
	@RequestMapping("/uploadCommonExcel")
	public String uploadCommonExcel(@RequestParam("fileId") MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
		ReturnMessage msg = new ReturnMessage();
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		try {
			InputStream fileInput = file.getInputStream();
			ByteArrayOutputStream fileOut = new ByteArrayOutputStream();
			byte[] b = new byte[1024];
			int len;
			while ((len = fileInput.read(b)) > -1) {
				fileOut.write(b, 0, len);
			}
			fileOut.flush();
			//获得文件名
            String fileName = file.getOriginalFilename();
            String path="我的文档";
            // 获取文件后缀名并转化为小写，用于后续比较
            String fileType = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()).toLowerCase();
            InputStream thumbsImg =null;
			String md5 = DigestUtils.md5Hex(file.getInputStream());
			BaseFileEntity existBaseFileEntity = baseFileEntityService.isExistFile(md5);
			if(existBaseFileEntity == null) {
				MinioClient minioClient = FileUtils.getInstance();
				boolean isExist = minioClient.bucketExists("lwzx");
				if (isExist) {
					System.out.println("Bucket already exists.");
				} else {
					// Make a new bucket called asiatrip to hold a zip file of photos.
					minioClient.makeBucket("lwzx");
				}
				// Upload  file to the bucket with putObject
				System.out.println("文件长度："+file.getSize());
				String newFileName=getUUID()+"."+fileType;
				//上传文件,如果是图片类型,处理缩略图上传到"我的图片/thumbs"
				 if(FileUtils.isImage(fileType)) {
			        	path="我的图片";
			        	InputStream thumInput = new BufferedInputStream(new ByteArrayInputStream(fileOut.toByteArray()));
			        	thumbsImg= ThumbnailatorUtils.getThumbsImg(thumInput);// 获取缩略图流
			        	thumInput.close();
			        	//创建目录thumbs
						minioClient.putObject("lwzx", path+"/"+this.getUserCode()+"/thumbs/"+newFileName,thumbsImg,thumbsImg.available(),"application/octet-stream");
						thumbsImg.close();
				 }
				InputStream orgInput = new BufferedInputStream(new ByteArrayInputStream(fileOut.toByteArray()));
				minioClient.putObject("lwzx",path+"/"+this.getUserCode()+"/"+newFileName, orgInput,orgInput.available(),"application/octet-stream");
				fileInput.close();
				BaseFileEntity baseFileEntity = new BaseFileEntity();
				baseFileEntity.setId(getUUID());
				baseFileEntity.setFileName(fileName);
				baseFileEntity.setFileNewName(newFileName);
				baseFileEntity.setFileDirectory("lwzx");
				baseFileEntity.setFilePath(path+"/"+this.getUserCode()+"/");
				baseFileEntity.setAbsolutePath(minioClient.getObjectUrl("lwzx", path+"/"+this.getUserCode()+"/"+newFileName));
				baseFileEntity.setFileSize(file.getSize());
				baseFileEntity.setFileType(fileType);
				baseFileEntity.setFileMd5(md5);
				baseFileEntity.setCreateUserCode(this.getUserCode());
				baseFileEntity.setCreateUserName(this.getUserEntity().getName());
				baseFileEntity.setCreateTime(new Date());
				baseFileEntity.setUpdateUserCode(this.getUserCode());
				baseFileEntity.setUpdateUserName(this.getUserEntity().getName());
				baseFileEntityService.saveFileInfo(baseFileEntity);
			}else {
				existBaseFileEntity.setFileName(fileName);
				baseFileEntityService.saveFileInfo(existBaseFileEntity);
			}
			//将路径设置到信息中
			msg.setInfo(path+"/"+this.getUserCode()+"/"+fileName);
			msg.setStatus("true");
			msg.setData(file.getOriginalFilename()+"上传成功");
			
			System.out.println(file.getOriginalFilename()+" is uploaded successfully");
		} catch (Exception e) {
			e.printStackTrace();
			msg.setStatus("false");
			msg.setData(e.toString());
		}
		return JSONObject.toJSONString(msg);
	}
	
	/**
	 * 获取文件上传的路径列表
	  * @Description .
	  * @author 李增冰[lizengbing] Tel13807031023
	  * @param request
	  * @param response
	  * @return
	 */
	@RequestMapping("/getCataLogue")
	public String getCataLogue(HttpServletRequest request,HttpServletResponse response) {
		List<CataLogue> list = null;
		try {
			list = cataLogueService.findFilePath();
		} catch (Exception e) {
			e.printStackTrace();;
		}
		return JSONObject.toJSONString(list);
	}
}
